﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using DevelopTool.Bll.WiFiFixatorBlls;
using DevelopTool.Common;
using DevelopTool.Forms.BaseForms;
using DevelopTool.Model.CommonModels;
using DevelopTool.Model.WiFiFixatorModels;
using Sunny.UI;

namespace DevelopTool.Forms.SystemToolForms
{
    /// <summary>
    /// wifi固定器
    /// </summary>
    public partial class WiFiFixatorForm : BaseUIPage
    {
        /// <summary>
        /// 当前选中的左侧WiFi对象
        /// </summary>
        private WiFiFixator currentSelectedWiFi_Left;

        /// <summary>
        /// 当前选中的右侧WiFi对象
        /// </summary>
        private WiFiFixator currentSelectedWiFi_Right;


        private System.Windows.Forms.Timer showLogListTimer;

        public WiFiFixatorForm()
        {
            InitializeComponent();
        }

        private void WiFiFixatorForm_Load(object sender,EventArgs e)
        {
            this.Disposed += this.WiFiFixatorForm_Disposed;

            if(Setting.WiFiFixator.WiFiConnectionPriority == 1) this.rdoWiFiConnectionPriority_1.Checked = true;
            else if(Setting.WiFiFixator.WiFiConnectionPriority == 2) this.rdoWiFiConnectionPriority_2.Checked = true;

            if(Setting.WiFiFixator.WiFiConnectionRules == 1) this.rdoWiFiConnectionRules_1.Checked = true;
            else if(Setting.WiFiFixator.WiFiConnectionRules == 2) this.rdoWiFiConnectionRules_2.Checked = true;

            this.upDownFixatorIntervalTime.Value = Setting.WiFiFixator.FixatorIntervalTime;

            this.cboAutoStartFixator.Checked = Setting.WiFiFixator.AutoStartFixator;

            this.backgroundWorker_GetWiFiList.RunWorkerAsync(true);//后台自动刷新WiFi列表

            #region 刷新WiFi监控日志
            this.showLogListTimer = new System.Windows.Forms.Timer
            {
                Interval = 100,
                Enabled = true//启动计时器
            };
            showLogListTimer.Tick += ShowLogListTimer_Tick;
            #endregion 刷新WiFi监控日志              
        }




        /// <summary>
        /// 加载日志
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ShowLogListTimer_Tick(object sender,EventArgs e)
        {
            LogModel wiFiFixatorLog = WiFiFixatorLogBll.GetLog();
            if(wiFiFixatorLog == null) return;
            string logStr = $"[{wiFiFixatorLog.OperTime.TimeString()}] {wiFiFixatorLog.LogStr}{Environment.NewLine}";
            this.codeEditorLog.ContentText = this.codeEditorLog.ContentText.Insert(0,logStr);

            //检测任务是否正在运行
            if(QuartzHelper.IsRun(Setting.WiFiFixator.FixatorSSID,"WiFiFixator"))
            {
                this.btnFixator.TagString = "1";
                this.btnFixator.Text = "停止监控";
                this.btnFixator.Symbol = 61517;
            }
            else
            {
                this.btnFixator.TagString = "0";
                this.btnFixator.Text = "开启监控";
                this.btnFixator.Symbol = 61515;
            }
        }



        /// <summary>
        /// 添加wifi项到展示组件中
        /// </summary>
        /// <param name="uiListBox"></param>
        /// <param name="wifi"></param>
        private void AddWiFiItemToListBox(UINavMenu uiListBox,WiFiFixator wifi)
        {
            if(string.IsNullOrEmpty(wifi.Name)) return;//不显示没有名称的WiFi

            if(uiListBox.Nodes.ContainsKey(wifi.Name)) return;

            //创建节点
            TreeNode treeNode = uiListBox.CreateNode($"{wifi.Name}",Guid.NewGuid());
            treeNode.Name = wifi.Name;
            treeNode.Tag = wifi;

            #region 设置信号强度图标
            Color tipsForeColor = uiListBox.ForeColor;
            int symbol = 0;
            if(wifi.SignalStrength <= 0)
            {
                symbol = 557818;//0
                tipsForeColor = Color.Red;
            }
            else if(wifi.SignalStrength <= 30)
                symbol = 560388;//1
            else if(wifi.SignalStrength > 30 && wifi.SignalStrength < 50)
                symbol = 560374;//2
            else if(wifi.SignalStrength >= 50 && wifi.SignalStrength < 70)
                symbol = 560385;//3
            else if(wifi.SignalStrength >= 70)
                symbol = 561541;//4
            uiListBox.SetNodeSymbol(treeNode,symbol,24);

            uiListBox.SetNodeTipsText(treeNode,$"{wifi.SignalStrength}%",uiListBox.FillColor,tipsForeColor);

            #endregion 设置信号强度图标

            if(wifi.IsSecure)//密码图标
            {
                uiListBox.AddNodeRightSymbol(treeNode,557825);
            }
            if(wifi.IsConnected)//已连接图标
            {
                uiListBox.AddNodeRightSymbol(treeNode,61452);
            }
            if(wifi.HasProfile)//已保存连接信息图标
            {
                uiListBox.AddNodeRightSymbol(treeNode,557697);
            }

            //还原上次的选择项
            if(this.currentSelectedWiFi_Left != null && this.currentSelectedWiFi_Left.Name == wifi.Name)
            {
                uiListBox.SelectedNode = treeNode;
            }

            if(this.currentSelectedWiFi_Right != null && this.currentSelectedWiFi_Right.Name == wifi.Name)
            {
                uiListBox.SelectedNode = treeNode;
            }
        }



        /// <summary>
        /// 开启/停止监控
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFixator_Click(object sender,EventArgs e)
        {
            if(this.btnFixator.TagString == "0")//开启监控 
            {
                if(string.IsNullOrEmpty(Setting.WiFiFixator.FixatorSSID))
                {
                    this.ShowWarningNotifier("请先选择需要监控的WiFi");
                    this.ShowWarningTip(this.btnFixator,$"请先把需要固定的WiFi添加到监控列表");
                    return;
                }

                QuartzHelper.DeleteJob(Setting.WiFiFixator.FixatorSSID,"WiFiFixator");

                //新增Quartz任务
                if(!QuartzHelper.AddSimpleTriggerJob(typeof(WiFiFixatorJob),Setting.WiFiFixator.FixatorSSID,"WiFiFixator",-1,
                    Setting.WiFiFixator.FixatorIntervalTime,DateTime.Now,DateTime.Now.AddYears(100)))
                {
                    this.ShowWarningNotifier("开启监控失败");
                    WiFiFixatorLogBll.AddLog(new LogModel(Model.Enums.LogType.Error,$"开启监控WiFi【{Setting.WiFiFixator.FixatorSSID}】失败"));
                }

                WiFiFixatorLogBll.AddLog(new LogModel(Model.Enums.LogType.Info,$"开启监控WiFi【{Setting.WiFiFixator.FixatorSSID}】"));
            }
            else//停止监控
            {
                QuartzHelper.DeleteJob(Setting.WiFiFixator.FixatorSSID,"WiFiFixator");//删除任务

                WiFiFixatorLogBll.AddLog(new LogModel(Model.Enums.LogType.Info,$"停止监控WiFi【{Setting.WiFiFixator.FixatorSSID}】"));
            }
        }


        /// <summary>
        /// 监控间隔时间 设置事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="value"></param>
        private void upDownFixatorIntervalTime_ValueChanged(object sender,int value)
        {
            Setting.WiFiFixator.FixatorIntervalTime = this.upDownFixatorIntervalTime.Value;

            if(string.IsNullOrEmpty(Setting.WiFiFixator.FixatorSSID)) return;

            //如果任务正在运行
            if(QuartzHelper.IsRun(Setting.WiFiFixator.FixatorSSID,"WiFiFixator"))
            {
                //修改Quartz任务触发规则
                if(!QuartzHelper.ModifySimpleTriggerJobTime(Setting.WiFiFixator.FixatorSSID,"WiFiFixator",-1,Setting.WiFiFixator.FixatorIntervalTime))
                {
                    this.ShowWarningNotifier("修改监控间隔时间失败");
                    WiFiFixatorLogBll.AddLog(new LogModel(Model.Enums.LogType.Error,$"调整WiFi【{Setting.WiFiFixator.FixatorSSID}】的监控间隔时间失败"));
                }
                else
                {
                    WiFiFixatorLogBll.AddLog(new LogModel(Model.Enums.LogType.Info,$"调整WiFi【{Setting.WiFiFixator.FixatorSSID}】的监控间隔时间为【{Setting.WiFiFixator.FixatorIntervalTime}秒】"));
                }
            }
        }


        /// <summary>
        /// 删除固定WiFi
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDeleteFixator_Click(object sender,EventArgs e)
        {
            TreeNode node = this.uiListBoxRight.SelectedNode;
            if(node == null) return;

            node.TreeView.Nodes.Remove(node);
            this.currentSelectedWiFi_Right = null;

            if(this.uiListBoxRight.Nodes.Count > 0)
            {
                this.btnDeleteFixator.Enabled = true;
            }
            else
            {
                this.btnDeleteFixator.Enabled = false;
            }

            if(this.uiListBoxRight.Nodes.Count > 1)
            {
                this.btnUp.Enabled = true;
                this.btnDown.Enabled = true;
            }
            else
            {
                this.btnUp.Enabled = false;
                this.btnDown.Enabled = false;
            }

            if(node.Tag is WiFiFixator wifi)
            {
                QuartzHelper.DeleteJob(wifi.Name,"WiFiFixator");//删除监控任务
                WiFiFixatorLogBll.AddLog(new LogModel(Model.Enums.LogType.Info,$"删除监控WiFi【{wifi.Name}】"));
            }

            Setting.WiFiFixator.FixatorSSID = string.Empty;

        }


        /// <summary>
        /// 清空日志
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClearLog_Click(object sender,EventArgs e)
        {
            this.codeEditorLog.ClearContent();
        }

        /// <summary>
        /// 新增固定WiFi
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddFixator_Click(object sender,EventArgs e)
        {
            if(this.currentSelectedWiFi_Left == null) return;
            AddFixatorWiFi(this.currentSelectedWiFi_Left);
        }

        /// <summary>
        /// 上移固定wifi
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUp_Click(object sender,EventArgs e)
        {
            TreeNode node = this.uiListBoxRight.SelectedNode;
            if(node == null || node.PrevNode == null) return;

            TreeNode newNode = (TreeNode)node.Clone();
            //节点的移动
            if(node.Parent != null)
                node.Parent.Nodes.Insert(node.PrevNode.Index,newNode);
            else
                node.TreeView.Nodes.Insert(node.PrevNode.Index,newNode);
            node.TreeView.SelectedNode = newNode;
            node.TreeView.Nodes.Remove(node);
        }

        /// <summary>
        /// 下移固定WiFi
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDown_Click(object sender,EventArgs e)
        {
            TreeNode node = this.uiListBoxRight.SelectedNode;
            if(node == null || node.PrevNode == null) return;

            TreeNode newNode = (TreeNode)node.Clone();
            //节点的移动
            if(node.Parent != null)
                node.Parent.Nodes.Insert(node.NextNode.Index + 1,newNode);
            else
                node.TreeView.Nodes.Insert(node.NextNode.Index + 1,newNode);
            node.TreeView.SelectedNode = newNode;
            node.TreeView.Nodes.Remove(node);
        }




        private void WiFiFixatorForm_Resize(object sender,EventArgs e)
        {
            LayoutWifiBox();
        }

        private void uiSplitContainer2_SplitterMoved(object sender,SplitterEventArgs e)
        {
            LayoutWifiBox();
        }

        /// <summary>
        /// 设置WiFi展示组件布局
        /// </summary>
        private void LayoutWifiBox()
        {
            int width = this.uiSplitContainer2.Panel1.Width / 2 - 25;
            this.uiTitlePanelLeft.Width = width;
            this.uiTitlePanelRigth.Width = width;
        }

        /// <summary>
        /// WiFi连接优先级 选择事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rdoWiFiConnectionPriority_CheckedChanged(object sender,EventArgs e)
        {
            if(!(sender is UIRadioButton radioButton)) return;
            //this.uiGroupBoxWiFiConnectionRules.Visible = radioButton.TagString.ToInt() == 1;//显示或隐藏【WiFi连接规则】选择组件
            Setting.WiFiFixator.WiFiConnectionPriority = radioButton.TagString.ToInt();
        }


        /// <summary>
        /// WiFi连接规则 选择事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rdoWiFiConnectionRules_CheckedChanged(object sender,EventArgs e)
        {
            if(!(sender is UIRadioButton radioButton)) return;
            Setting.WiFiFixator.WiFiConnectionRules = radioButton.TagString.ToInt();
        }



        /// <summary>
        /// 自动开启监控 选择事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cboAutoStartFixator_CheckedChanged(object sender,EventArgs e)
        {
            Setting.WiFiFixator.AutoStartFixator = this.cboAutoStartFixator.Checked;
        }


        /// <summary>
        /// 在左侧列表中选中某个WiFi事件
        /// </summary>
        /// <param name="node"></param>
        /// <param name="item"></param>
        /// <param name="pageIndex"></param>
        private void uiListBoxLeft_MenuItemClick(TreeNode node,NavMenuItem item,int pageIndex)
        {
            if(!(node.Tag is WiFiFixator wifi)) return;
            this.currentSelectedWiFi_Left = wifi;

            if(string.IsNullOrEmpty(wifi.ProfileXML))
            {
                uiSplitContainer1.Panel2Collapsed = true;
            }
            else
            {
                uiSplitContainer1.Panel2Collapsed = false;

                this.codeEditorWifiInfo.ContentText = wifi.ProfileXML;
                this.codeEditorWifiInfo.PanelTitle = wifi.Name;
            }
        }

        /// <summary>
        /// 在右侧列表中选中某个WiFi事件
        /// </summary>
        /// <param name="node"></param>
        /// <param name="item"></param>
        /// <param name="pageIndex"></param>
        private void uiListBoxRight_MenuItemClick(TreeNode node,NavMenuItem item,int pageIndex)
        {
            if(!(node.Tag is WiFiFixator wifi)) return;
            this.currentSelectedWiFi_Right = wifi;
        }


        private void uiListBoxLeft_NodeMouseDoubleClick(object sender,TreeNodeMouseClickEventArgs e)
        {
            if(!(e.Node.Tag is WiFiFixator wifi)) return;
            AddFixatorWiFi(wifi);
        }

        private void AddFixatorWiFi(WiFiFixator wifi)
        {
            this.uiListBoxRight.Nodes.Clear();//目前只能监控一个，后面再实现监控多个吧

            if(!wifi.HasProfile)
            {
                string tips = $"WiFi【{wifi.Name}】不存在网络配置文件，请先在系统右下角网络管理器中连接该WiFi后再固定";
                this.ShowWarningNotifier(tips);
                WiFiFixatorLogBll.AddLog(new LogModel(Model.Enums.LogType.Warning,$"{tips}"));
                return;
            }

            AddWiFiItemToListBox(this.uiListBoxRight,wifi);

            if(this.uiListBoxRight.Nodes.Count > 0)
            {
                this.btnDeleteFixator.Enabled = true;
            }
            else
            {
                this.btnDeleteFixator.Enabled = false;
            }

            if(this.uiListBoxRight.Nodes.Count > 1)
            {
                this.btnUp.Enabled = true;
                this.btnDown.Enabled = true;
            }
            else
            {
                this.btnUp.Enabled = false;
                this.btnDown.Enabled = false;
            }

            Setting.WiFiFixator.FixatorSSID = wifi.Name;
        }


        #region 后台刷新展示WiFi列表

        private void backgroundWorker_GetWiFiList_DoWork(object sender,System.ComponentModel.DoWorkEventArgs e)
        {
            bool repeatGet = (bool)e.Argument;
            do
            {
                try
                {
                    List<WiFiFixator> wifiList = new WifiHelper().GetWiFiList(true);
                    backgroundWorker_GetWiFiList.ReportProgress(1,wifiList);
                }
                catch(Exception ex)
                {
                    backgroundWorker_GetWiFiList.ReportProgress(0,$"获取WiFi列表失败：{ex.Message}");
                }
                finally
                {
                    Thread.Sleep(5000);//5秒刷新一次
                }
            } while(repeatGet);
        }


        private void backgroundWorker_GetWiFiList_ProgressChanged(object sender,System.ComponentModel.ProgressChangedEventArgs e)
        {
            this.uiListBoxLeft.Nodes.Clear();//清空WiFi列表

            if(e.ProgressPercentage == 0)
            {
                WiFiFixatorLogBll.AddLog(new LogModel(Model.Enums.LogType.Error, e.UserState.ToString()));
            }
            else if(e.ProgressPercentage == 1)
            {
                if(!(e.UserState is List<WiFiFixator> wifiList)) return;

                foreach(WiFiFixator wifi in wifiList)
                {
                    AddWiFiItemToListBox(this.uiListBoxLeft,wifi);
                }

                //刷新右边WiFi列表（监控列表）
                if(!string.IsNullOrEmpty(Setting.WiFiFixator.FixatorSSID))
                {
                    WiFiFixator currentWiFiFixator = wifiList.FirstOrDefault(it => it.Name == Setting.WiFiFixator.FixatorSSID) ?? new WiFiFixator()
                    {
                        Name = Setting.WiFiFixator.FixatorSSID,
                        SignalStrength = -1,
                        HasProfile = true,
                        IsSecure = false,
                        IsConnected = false,
                        ProfileXML = string.Empty
                    };
                    AddFixatorWiFi(currentWiFiFixator);
                }

            }
        }

        #endregion 后台刷新WiFi列表


        private void WiFiFixatorForm_Disposed(object sender,EventArgs e)
        {
            if(this.showLogListTimer != null)
            {
                this.showLogListTimer.Stop();
                this.showLogListTimer.Dispose();
            }


            try
            {
                this.backgroundWorker_GetWiFiList.CancelAsync();
                this.backgroundWorker_GetWiFiList.Dispose();
            }
            catch(Exception ex)
            {
                LogHelper.WriteErrLog(ex);
            }
        }
    }
}
